import { Button, message, Modal, Spin } from 'antd';
import Icon from '@app/components/Icon';
import { useCallback, useEffect, useState } from 'react';
import { observer } from 'mobx-react-lite';
import { CopyToClipboard } from 'react-copy-to-clipboard';
import MonacoEditor from '@app/components/MonacoEditor';

import { useStore } from '@app/stores';
import { handleKeyword } from '@app/utils/function';
import { useI18n } from '@vesoft-inc/i18n';
import styles from './index.module.less';

interface IProps {
  space: string;
  open: boolean;
  onCancel?: () => void;
}

const sleepGql = `:sleep 20;`;
const DDLModal = (props: IProps) => {
  const { space, open, onCancel } = props;
  const { intl } = useI18n();
  const [loading, setLoading] = useState(false);
  const {
    schema: { getSchemaDDL },
  } = useStore();
  const [ddl, setDDL] = useState('');
  const handleJoinGQL = useCallback((data) => data.map((i) => i.replaceAll('\n', '')).join(';\n'), []);

  const handleOpen = useCallback(async () => {
    setLoading(true);
    const ddlMap = await getSchemaDDL(space);
    if (ddlMap) {
      const { tags, edges, indexes } = ddlMap;
      let content = `# Create Space \n${ddlMap.space.replace(
        /ON default_zone_(.*)+/gm,
        '',
      )};\n${sleepGql}\nUSE ${handleKeyword(space)};`;
      if (tags.length) {
        content += `\n\n# Create Tag: \n${handleJoinGQL(tags)};`;
      }
      if (edges.length) {
        content += `\n\n# Create Edge: \n${handleJoinGQL(edges)};`;
      }

      if (indexes.length) {
        if (tags.length || edges.length) {
          content += `\n${sleepGql}`;
        }
        content += `\n\n# Create Index: \n${handleJoinGQL(indexes)};`;
      }
      setDDL(content);
    }
    setLoading(false);
  }, [space]);

  const handleCopy = useCallback(() => {
    message.success(intl.get('common.copySuccess'));
  }, []);

  const handleDownload = useCallback(() => {
    let url = '#';
    const _utf = '\uFEFF';
    if (window.Blob && window.URL && window.URL.createObjectURL) {
      const csvBlob = new Blob([_utf + ddl], {
        type: 'text/csv',
      });
      url = URL.createObjectURL(csvBlob);
    }
    url = 'data:attachment/csv;charset=utf-8,' + _utf + encodeURIComponent(ddl);
    const link = document.createElement('a');
    link.href = url;
    link.download = `${space}_ddl.ngql`;
    link.click();
  }, [space, ddl]);

  useEffect(() => {
    if (open) {
      handleOpen();
    } else {
      setDDL('');
    }
  }, [open]);

  return (
    <Modal
      className={styles.ddlModal}
      destroyOnClose={true}
      open={open}
      width={'60%'}
      bodyStyle={{ minHeight: 200 }}
      onCancel={onCancel}
      title={intl.get('schema.showDDL')}
      footer={
        !loading && (
          <div className={styles.footer}>
            <Button key="confirm" type="primary" disabled={!ddl} onClick={handleDownload}>
              {intl.get('schema.downloadNGQL')}
            </Button>
          </div>
        )
      }
    >
      <Spin spinning={loading}>
        {!loading && (
          <div className={styles.modalItem}>
            <CopyToClipboard key={1} text={ddl} onCopy={handleCopy} disabled={!ddl}>
              <Button className={styles.duplicateBtn} key="confirm" icon={<Icon type="icon-Duplicate" />}>
                {intl.get('common.duplicate')}
              </Button>
            </CopyToClipboard>
            <MonacoEditor value={ddl} readOnly />
          </div>
        )}
      </Spin>
    </Modal>
  );
};

export default observer(DDLModal);